from flask_records.decorators import query_by_page, query
from common.utils.utils import custom_marshal_pagination

GET_BY_PAGE_SQL = """
select *
from operation_log
where (is_active = :is_active or :is_active is null)
  and (
            lower(operation_log.notes) like lower(:search_str_re) or
            lower(operation_log.operation_log_type) like lower(:search_str_re) or
            lower(operation_log.action_str) like lower(:search_str_re) or
            :search_str_re is null
    )  
  and (operation_log_type = :operation_log_type or :operation_log_type is null)
  and (parent_id = :parent_id or :parent_id is null)
  and (action_str = :action_str or :action_str is null)
  and (creator_id = :creator_id or :creator_id is null)  
  and (operation_log.create_datetime >= :date_begin or :date_begin is null)
  and (to_char(operation_log.create_datetime, 'yyyy-MM-dd') <= :date_end or :date_end is null)

"""


def get_by_page(page, page_size, sorted_by, sorted_by_type, search_str, **kwargs):
    sql = GET_BY_PAGE_SQL
    order_by_sql = "{} ORDER BY {} {}".format(sql, sorted_by, sorted_by_type)

    if search_str:
        search_str_re = '%{}%'.format(search_str)
    else:
        search_str_re = None

    @query_by_page(order_by_sql, page_size=page_size)
    def _get_by_pagination(
            page, search_str_re, operation_log_type, parent_id, action_str, creator_id, date_begin, date_end,
            is_active, is_delete):
        pass

    pagination = _get_by_pagination(
        page=page, search_str_re=search_str_re, **kwargs
    )
    pagination = custom_marshal_pagination(pagination)
    return pagination
